import { ExceptionFilter, Catch, ArgumentsHost, BadRequestException } from '@nestjs/common';
import type { ILanguageService } from '@wwjCommon/language/language.interface';
import { Inject } from '@nestjs/common';

/**
 * 验证异常过滤器
 * 将class-validator的错误转换为多语言消息
 * 符合NestJS规范的异常处理方式
 */
@Catch(BadRequestException)
export class ValidationExceptionFilter implements ExceptionFilter {
  constructor(@Inject('ILanguageService') private readonly languageService: ILanguageService) {}

  async catch(exception: BadRequestException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse() as any;

    // 如果是验证错误，尝试转换为多语言消息
    if (exceptionResponse.message && Array.isArray(exceptionResponse.message)) {
      const translatedMessages = await this.translateValidationMessages(exceptionResponse.message);
      
      response.status(status).json({
        code: 0,
        msg: translatedMessages.join('; '),
        data: null,
        timestamp: new Date().toISOString(),
      });
    } else {
      // 其他错误直接返回
      response.status(status).json({
        code: 0,
        msg: exceptionResponse.message || '请求参数错误',
        data: null,
        timestamp: new Date().toISOString(),
      });
    }
  }

  /**
   * 翻译验证错误消息
   */
  private async translateValidationMessages(messages: string[]): Promise<string[]> {
    const translatedMessages: string[] = [];

    for (const message of messages) {
      try {
        // 尝试从验证错误消息中提取字段名和规则
        const fieldMatch = message.match(/^(\w+)\s+(.+)$/);
        if (fieldMatch) {
          const [, field, rule] = fieldMatch;
          
          // 根据字段名和规则获取多语言消息
          let translatedMessage: string;
          
          if (rule.includes('should not be empty')) {
            translatedMessage = await this.languageService.getValidateMessage(
              `validate_user.${field}_require`,
              { attribute: field }
            );
          } else if (rule.includes('must be longer than')) {
            const minMatch = rule.match(/must be longer than (\d+)/);
            const min = minMatch ? minMatch[1] : '6';
            translatedMessage = await this.languageService.getValidateMessage(
              `validate_user.${field}_min`,
              { attribute: field, min }
            );
          } else if (rule.includes('must be shorter than')) {
            const maxMatch = rule.match(/must be shorter than (\d+)/);
            const max = maxMatch ? maxMatch[1] : '20';
            translatedMessage = await this.languageService.getValidateMessage(
              `validate_user.${field}_max`,
              { attribute: field, max }
            );
          } else if (rule.includes('must be an email')) {
            translatedMessage = await this.languageService.getValidateMessage(
              `validate_user.${field}_format`,
              { attribute: field }
            );
          } else {
            // 默认使用原始消息
            translatedMessage = message;
          }
          
          translatedMessages.push(translatedMessage);
        } else {
          translatedMessages.push(message);
        }
      } catch (error) {
        // 如果翻译失败，使用原始消息
        translatedMessages.push(message);
      }
    }

    return translatedMessages;
  }
}
